# -*- coding: utf-8 -*-
from django.db.models import Q
from rest_framework import serializers

from app.emergency.models import AreaPlan
from dvadmin.system.models import Structures, RoadsInfos
from dvadmin.utils.json_response import SuccessResponse, DetailResponse, ErrorResponse
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet


class AreaPlanSerializer(CustomModelSerializer):
    """
    区域预案-序列化器
    """
    struct_name = serializers.CharField(source='struct.sname', read_only=True)
    plan_name = serializers.CharField(source='plan.name', read_only=True)

    class Meta:
        model = AreaPlan
        fields = "__all__"
        read_only_fields = ["id"]


class AreaPlanCreateUpdateSerializer(CustomModelSerializer):
    """
    操作区域预案  创建/更新时的列化器
    """

    class Meta:
        model = AreaPlan
        fields = '__all__'


class AreaPlanViewSet(CustomModelViewSet):
    """
    区域预案接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = AreaPlan.objects.order_by('-create_datetime')
    serializer_class = AreaPlanSerializer

    def get_plan_by_road(self, request, *args, **kwargs):
        '''
            get:
            根据传入路段id，获取路段构造物其下预案信息
        '''
        road = RoadsInfos.objects.filter(id=kwargs.get('pk')).first()
        instance = AreaPlan.objects.filter(struct__roadid=road)

        if instance:
            response = AreaPlanSerializer(instance=instance, many=True, request=request)
            total = len(response.data)
            data = dict(road_name=road.cname, road_id=road.id, plan=response.data)
            return SuccessResponse(data=data, total=total, msg="获取成功")
        else:
            return ErrorResponse(msg="数据不存在")

    def get_plan_by_struct(self, request, *args, **kwargs):
        '''
            根据传入构造物id，获取构造物其下预案信息
        '''
        struct = Structures.objects.filter(id=kwargs.get('pk')).first()
        instance = AreaPlan.objects.filter(struct=struct)
        if instance:
            response = AreaPlanSerializer(instance=instance, many=True, request=request)
            total = len(response.data)
            data = dict(road_name=struct.roadid.cname, road_id=struct.roadid.id, plan=response.data)
            return SuccessResponse(data=data, total=total, msg="获取成功")
        else:
            return ErrorResponse(msg="数据不存在")
